package org.example.filter;

import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.config.JwtConfig;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @Auther:Liu
 * @Testname:IsLoginGlobalFilter
 * @Date:2025/9/16 20:37
 */
@Component
@Slf4j
public class IsLoginGlobalFilter implements GlobalFilter, Ordered {

    private StringRedisTemplate stringRedisTemplate;
    private ValueOperations<String, String> valueOperations;

    @Autowired
    public IsLoginGlobalFilter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        valueOperations = stringRedisTemplate.opsForValue();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始校验用户是否登录..");
        ServerHttpRequest request = exchange.getRequest();
        // 1.判断用户访问路径
        URI uri = request.getURI();
        log.info("用户访问的路径是：{}", uri.getPath());
        if (uri.getPath().contains("/auth")) {
            log.info("用户访问登陆接口，不需要登陆，直接访问！");
            return chain.filter(exchange);
        }
        // 2.获取用户的token
        List<String> tokens = request.getHeaders().get("token");
        log.info("tokens:{}", tokens);
        if (tokens == null || tokens.isEmpty()) {
            return fail(exchange);
        }
        String token = tokens.get(0);
        log.info("token:{}", token);
        Claims claims = JwtConfig.parseJWT(token);
        log.info("claims:{}", claims);
        String id = claims.get("id").toString();
        log.info("id:{}", id);
        try {
            String redisToken = valueOperations.get("token:" + id);
            log.info("redisToken:{}", redisToken);
            if (!Objects.equals(redisToken, token)) {
                return fail(exchange);
            }
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("token解析失败: {}", e.getMessage());
            return fail(exchange);
        }
    }

    @SneakyThrows
    private Mono<Void> fail(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(403, "用户没有登陆");
        String str = JSONArray.toJSONString(result);
        DataBuffer data =
                response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        log.info("⽤户未携带token,{}", str);
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
